<template>
    <div class="top">
        <el-icon @click="goBack()" :size="20">
            <Close />
        </el-icon>
        <el-text class="mx-1">帮助</el-text>
    </div>

    <div class="main">
        <h2 style="margin-left: 20px;">账号登录</h2>
        <div class="login-type-switch">
            <span :class="{ active: loginType === 'account' }" @click="switchLoginType('account')">账号登录</span>
            <span :class="{ active: loginType === 'phone' }" @click="switchLoginType('phone')">手机号登录</span>
        </div>
        <div class="form">
            
            <el-form ref="formRef" style="width: 90%;" :model="userLoginDTO" label-width="auto">
                <template v-if="loginType === 'account'">
                    <el-form-item style="width: 100%;" prop="account" :rules="[{ required: true, message: '请输入账号' },{ type: 'number', message: '账号请输入数字' },]">
                        <div class="custom-input" style="width: 100%; ">
                            <el-input v-model.number="userLoginDTO.account" placeholder="请输入账号" />
                        </div>
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item style="width: 100%;" prop="phone" :rules="[{ required: true, message: '请输入手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }]">
                        <div class="custom-input" style="width: 100%; ">
                            <el-input v-model="userLoginDTO.phone" placeholder="请输入手机号" />
                        </div>
                    </el-form-item>
                </template>
                <el-form-item prop="password" :rules="[{ required: true, message: '请输入密码' },]">
                    <div class="custom-input" style="width: 100%;">
                        <el-input v-model="userLoginDTO.password" type="password" placeholder="请输入密码" show-password />
                    </div>
                </el-form-item>
            </el-form>
            

            <div class="login-btn">
                <div class="btn">
                    <el-button @click="Login(formRef)"
                        type="primary" round 
                        style="width: 90%; height: 50px; border-radius: 100px; font-size: 18px; letter-spacing: 5px;" >
                        登录
                    </el-button>
                </div>
                <div class="btn" @click="Register()">
                    <el-button key="plain" round
                        style="width: 90%; height: 50px; border-radius: 100px; font-size: 18px; letter-spacing: 5px;">
                        注册
                    </el-button>
                </div>
            </div>

            <div class="login-option">
                <a href="#">忘记密码</a>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="agree">
                <label for="agree">我已阅读并同意<a href="#">《万象协议》</a><a href="#">《个人信息保护指引》</a></label>
            </div>
        </div>
    </div>

    <div class="bottom">
        <div class="iconBox">
            <img src="@/assets/icon/weChat.svg" style="width: 50px;">
            <img src="@/assets/icon/QQ.svg" style="width: 50px;">
            <img src="@/assets/icon/weiBo.svg" style="width: 50px;">
        </div>
    </div>
</template>

<script lang="ts" setup>
import { Close } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ref,inject } from 'vue'
import api from '@/api';
import { useRouter } from 'vue-router';
import { UserStore } from '@/stores/userInfoStore';
import { TipStore } from '@/stores/tipStore';

const disableCacheFor = inject('disableCacheFor') as (componentNameList: string[]) => void;
const router = useRouter();
const userStoreObject = UserStore();
const TipStoreObject = TipStore();


// 登录类型：account-账号登录，phone-手机号登录
const loginType = ref('account');

// 切换登录类型
const switchLoginType = (type) => {
    loginType.value = type;
    // 切换登录类型时清空表单
    userLoginDTO.value = {
        account: null,
        phone: '',
        password: null
    };
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

const userLoginDTO = ref({
    account: null,
    phone: '',
    password: null,
});

const goBack = () => {
  router.push('/Profile');
}

const formRef = ref<FormInstance>()
const Login = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            // 根据登录类型调用不同的登录方法
            let loginPromise;
            if (loginType.value === 'account') {
                // 账号登录
                loginPromise = api.UserLogin(userLoginDTO.value.account, null, userLoginDTO.value.password);
            } else {
                // 手机号登录
                loginPromise = api.UserLogin(null, userLoginDTO.value.phone, userLoginDTO.value.password);
            }

            loginPromise.then(async(res) => {
                if(res.data.code == 1){
                    TipStoreObject.successTip("登录成功");
                    localStorage.removeItem("wanXiang_userInfo"); //如果之前版本是存在本地，之后的版本不是，可以靠这种办法删除存留在浏览器的数据

                    //1.将jwt令牌存入本地存储中
                    localStorage.setItem('wx_access-client', res.data.data)

                    //2.根据令牌获取用户信息，存入pinia仓库，pinia仓库不持久化存储用户的信息
                    await api.ParseJwt(res.data.data).then(r => {
                        userStoreObject.setUserInfo(r.data.data);
                        disableCacheFor(['Profile','Works']) //刷新组件的挂载，因为数据更新了
                        router.push({path: '/Profile',});
                    }).catch(err => {
                        console.log("令牌解析失败",err);
                    })
                  
                   
                    //3.如果pinia仓库中的用户信息没了，就重新使用jwt令牌获取用户信息（jwt令牌过期时间为24小时），如果获取失败，就提示用户重新登录
                    //4.平时的发送接口有必要使用jwt吗？用pinia仓库的用户id值判断不就行了


                }else if (res.data.code == 0){
                    TipStoreObject.errorTip(res.data.msg);
                }
            }).catch((err) => {
                console.log("未知错误:",err);
            })
        } else {}
    })
}

//注册
const Register = () => {
    router.push('/Register');
}

</script>

<style scoped>
.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    padding: 0px 12px;
}

.mx-1 {
    font-size: 15px;
    margin-right: 10px;
}

.main {
    margin-top: 40px;
    height: auto;
}

.form {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 70px;
    flex-direction: column;
}
:deep(.el-form-item){
    margin-bottom: 35px;
}
.custom-input{
    display: flex;
}
.custom-input :deep(.el-input__wrapper) {
    background: transparent;
    box-shadow: none !important;
    border-radius: 0;
    padding-left: 0;
    border-bottom: 1px solid #dcdfe6;
}
.custom-input :deep(.el-input__wrapper.is-focus) {
    border-bottom-color: #409eff;
}

.custom-input :deep(.el-input__inner) {
    color: #333;
    font-size: 16px;
}

.custom-input :deep(.el-input__inner::placeholder) {
    color: #999;
    font-weight: 300;
    transition: opacity 0.2s;
}

.custom-input :deep(.el-input__inner:focus::placeholder) {
    opacity: 0;
}

.login-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    margin-top: 20px;
    flex-direction: column;
}

.btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
}

.login-option {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
}

.login-option a {
    color: #0084ff;
    text-decoration: none;
    font-size: 14px;
}

.login-option a.active {
    color: #1a1a1a;
    font-weight: 600;
}

.login-type-switch {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    margin-bottom: 20px;
}

.login-type-switch span {
    padding: 8px 20px;
    margin: 0 10px;
    cursor: pointer;
    color: #646464;
    position: relative;
}

.login-type-switch span.active {
    color: #0084ff;
    font-weight: 600;
}

.login-type-switch span.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 2px;
    background-color: #0084ff;
}

.checkbox-group {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #646464;
    margin-top: 20px;
}

.checkbox-group input {
    margin-right: 8px;
}

.checkbox-group a {
    color: #0084ff;
    text-decoration: none;
}

.bottom {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: auto;
    margin-top: 70px;
}

.iconBox {
    width: 80%;
    display: flex;
    justify-content: space-between;
}

</style>
